<?php

namespace App\Http\Controllers\User;

use App\Http\Requests\ArticleRequest;
use App\Models\Brand;
use App\Models\Department;
use App\Models\Role;
use App\User;
use DB;
use Illuminate\Support\Facades\Session;
use Qiniu\Auth as qAuth;
use Illuminate\Support\Facades\Auth;
use App\Models\Article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Qiniu\Storage\UploadManager;

class ArticleController extends Controller
{
    public function index(){
        $id = Auth::user()->roles_id;
        if($id==1){
            $article = Article::where(['active'=>'0'])->where('partid',Auth::user()->partid)->orderBy('id','desc')->paginate(5);
            return view('akl.admin.article_index', ['article' => $article]);
        }
        $article = Article::where(['users_id'=>Auth::user()->id,'active'=>'0'])->where('partid',Auth::user()->partid)->orderBy('id','desc')->paginate(5);
        return view('akl.admin.article_index')->with('article',$article);
    }

    public function show(){
        return view('akl.admin.article_add');
    }

    public function create(ArticleRequest $request){
        if(!$request->file('file')[0]){
            return back()->with('errors','缩略图不能为空');
        }
        $content = $this->parthContent();
        $inp = array(
            'title'=>Input::all()['title'],
            'location'=>Input::all()['location'],
            'class'=>Input::all()['class'],
            'content'=>$content,
            'users_id'=>Auth::user()->id,
            'thumbnail'=>$request->get('imgs')[0],
            'partid'=>Auth::user()->partid,
        );
        $rel = Article::create($inp);
        if($rel->wasRecentlyCreated) return back()->withErrors('errors','添加成功');
        return back()->withErrors( 'errors','添加失败');
    }

    public function destroy($atcid){
        $id = Auth::user()->roles_id;
        if($id==1){
            $rel = DB::table('articles')->where('id',$atcid)->where('partid',Auth::user()->partid)->update(['active' =>'1']);
            if(!$rel) return back()->with('errors','删除失败');
            return back()->with('errors','删除成功');
        }
        $id = Auth::user()->id;
        if( $id!= Article::find($atcid)->users_id) return back()->with('errors','你无此权限');
        $rel = DB::table('articles')->where('id',$atcid)->update(['active' =>'1']);
        if(!$rel) return back()->with('errors','删除失败');
        return back()->with('errors','删除成功');
    }

    public function update($atcid){
        $id = Auth::user()->roles_id;
        if($id==1){
            $rel = DB::table('articles')->where('id',$atcid)->where('partid',Auth::user()->partid)->first();
            if(!$rel)return redirect('index');
            return view('akl.admin.Article_update')->with( 'info',$rel);
        }
        if(!Article::hasUser($atcid)){
            return back()->with('errors','你无此文章');
        }
        $rel = Article::where('id',$atcid)->where('partid',Auth::user()->partid)->first();
        return view('akl.admin.Article_update')->with( 'info',$rel);
    }

    public function postUpdate(Request $request,$id){
        if($request->get('admin')||Article::hasUser($id)){
            if($this->doUp($request,$id))return back()->with('errors','更新成功');
            return back()->with('errors','更新失败');
        }
        return back()->with('errors','你无此权限');
    }

    private function doUp($request,$id){
        $inp = array(
            'title'=>Input::all()['title'],
            'class'=>Input::all()['class'],
            'content'=>$this->parthContent(),
            'thumbnail'=>$request->get('imgs')[0]
        );
        if(!$request->file('file')[0]){
            $inp['thumbnail'] = Article::find($id)->thumbnail;
        }
        return Article::where('id',$id)->where('partid',Auth::user()->partid)->update($inp);
    }

    public function parthContent(){
        $rel = Input::all()['content'];
        $xx = explode('<img src="/Uploads/image/',$rel);
        $arrxx = array();
        for( $i=1;$i<count($xx);$i++){
            $arrxx[] = "C:\Users\admin\PhpstormProjects\untitled\lara4\laravel\public\Uploads\image\\".str_replace('/','\\',mb_substr($xx[$i],0,29));
        }
        $accessKey = 'REGLFp0vy53PLg-szJvTHE_NJhBKTSyQ8fTVeA-S';
        $secretKey = 'YR2jV9TCzxOPNtOtqhd4yOk33zS2iX5qYNnMcDKx';
        $bucket = 'licheng';
        for( $i=0;$i<count($arrxx);$i++ ){
            $auth = new qAuth($accessKey, $secretKey);
            $token = $auth->uploadToken($bucket);
            $filePath = $arrxx[$i];
            $key = time().rand(999,9999).".jpg";
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return back()->with('error','图片上传出错，请重试') ;
            } else {
                $str = "<img src='http://ohv2zs4x6.bkt.clouddn.com/".$ret['key']."'/>";
                $rel = preg_replace("/<img src=\"\/Up.+?\"\/\>/s", "$str", $rel,1);
            }
        }
        return $rel;
    }

    /**
     * 首页展示6个案例
     * @return $this
     */

    public function showAll(){
        $article = Article::where('partid',session()->get('doain')->id)->where('active','0')->orderBy('id','desc')->paginate(6);
        $water = base64_encode(session()->get('doain')->water);
        $brands = Brand::where('partid',session()->get('doain')->id)->where('active','0')->orderBy('id','desc')->get()->take(8);
        for ( $i=0;$i<count($brands);$i++ ){
            $brands[$i]->logo=$brands[$i]->logo."?watermark/2/text/".$water."/font/5a6L5L2T/fontsize/500/fill/#000000=/dissolve/50/gravity/SouthEast/dx/0/dy/0";
        }
        $last = ".jpg?watermark/2/text/".$water."/font/5a6L5L2T/fontsize/500/fill/#000000=/dissolve/50/gravity/SouthEast/dx/0/dy/0";
        for ( $i=0;$i<count($article);$i++ ){
            $content = preg_replace("/(.jpg)/", $last, $article[$i]->content);
            $thumbnail = preg_replace("/(.jpg)/", $last, $article[$i]->thumbnail);
            $article[$i]->content=$content;
            $article[$i]->thumbnail=$thumbnail;
            $article[$i]->displayname=$article[$i]->user->displayname;
        }
        return view('akl.Aikla.Index-index',compact('brands','article'));
    }

    /**
     * 知识首页
     * @return $this
     */
    public function NoteIndex(){
        $article = Article::where('partid',session()->get('doain')->id)->where('active','0')->where('classid','2')->orderBy('id','desc')->paginate(10);
        $water = base64_encode(session()->get('doain')->water);
        $last = ".jpg?watermark/2/text/".$water."/font/5a6L5L2T/fontsize/500/fill/#000000=/dissolve/50/gravity/SouthEast/dx/0/dy/0";
        for ( $i=0;$i<count($article);$i++ ){
            $content = preg_replace("/(.jpg)/", $last, $article[$i]->content);
            $thumbnail = preg_replace("/(.jpg)/", $last, $article[$i]->thumbnail);
            $article[$i]->content=$content;
            $article[$i]->thumbnail=$thumbnail;
            $article[$i]->displayname=$article[$i]->user->displayname;
        }
        return view('akl.Aikla.Note-index')->with('article',$article);
    }

    /**
     * 案例首页
     * @return $this
     */
    public function CaseIndex(){
        $role = Role::where('partid',session()->get('doain')->id)->where('name','设计师')->first();
        $users = User::where('partid',session()->get('doain')->id)->where('active','0')->where('roles_id',$role->id)->get();
        $ids='';
        for ( $i=0;$i<count($users);$i++ ){
            $ids[] = $users[$i]->id;
        }
        $article = Article::where('partid',session()->get('doain')->id)->where('active','0')->whereIn('users_id', $ids)->orderBy('id','desc')->paginate(9);
        $water = base64_encode(session()->get('doain')->water);
        $last = ".jpg?watermark/2/text/".$water."/font/5a6L5L2T/fontsize/500/fill/#000000=/dissolve/50/gravity/SouthEast/dx/0/dy/0";
        for ( $i=0;$i<count($article);$i++ ){
            $content = preg_replace("/(.jpg)/", $last, $article[$i]->content);
            $thumbnail = preg_replace("/(.jpg)/", $last, $article[$i]->thumbnail);
            $article[$i]->content=$content;
            $article[$i]->thumbnail=$thumbnail;
            $article[$i]->displayname=$article[$i]->user->displayname;
        }
        return view('akl.Aikla.Case-index')->with('article',$article);
    }


    /**
     * 展示指定的一片文章
     * @param $id
     * @return $this
     */
    public function showOne(){
        $id =  explode('/',url()->current())[4];
        $article = Article::where('partid',session()->get('doain')->id)->where('active','0')->find($id);
        $water = base64_encode(session()->get('doain')->water);
        $last = ".jpg?watermark/2/text/".$water."/font/5a6L5L2T/fontsize/500/fill/#000000=/dissolve/50/gravity/SouthEast/dx/0/dy/0";
        $content = preg_replace("/(.jpg)/", $last, $article->content);
        $thumbnail = preg_replace("/(.jpg)/", $last, $article->thumbnail);
        $article->content=$content;
        $article->thumbnail=$thumbnail;
        $article->displayname=$article->user->displayname;
        return view('akl.Aikla.Note-detail')->with('article',$article);
    }

}




//            $article = Article::find($atcid)->update(['active'=>'1']);
